<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-10 15:07:49
 * @LastEditTime: 2023-07-10 13:30:43
 * @LastEditors: Please set LastEditors
 * @Description: 奖惩信息管理页面
-->
<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="134"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-save="false"
        :has-edit="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="88%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="category" label="信息类别">
          <template slot-scope="scope">
            <span v-if="scope.row.category === 'PUNISH'">惩罚</span>
            <span v-if="scope.row.category === 'REWARD'">奖励</span>
          </template>
        </el-table-column>
        <el-table-column prop="lessee.lesseeName" label="姓名" />
        <el-table-column prop="details" label="具体内容" />
        <el-table-column
          prop="rewardDate"
          :formatter="dateFormat"
          label="奖惩时间"
          min-width="100"
        />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.rewardRecordId" slot-scope="scope">
            <el-button
              v-if="judgePermission(134, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(134, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row.rewardRecordId)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- 展示图片 -->
      <el-dialog
        :title="titleText + '奖惩信息'"
        :visible.sync="dialogFormVisible"
        width="30%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="信息类别:" prop="category" class="w50p">
            <el-select v-model="formData.category" clearable>
              <el-option label="奖励" value="REWARD" />
              <el-option label="惩罚" value="PUNISH" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名:" prop="lesseeNo" class="w50p">
            <el-select v-model="formData.lesseeNo" clearable filterable>
              <el-option
                v-for="item in lessesArr"
                :key="item.lesseeNo"
                :label="item.lesseeName"
                :value="item.lesseeNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分数:" prop="integral" class="w50p">
            <el-input v-model="formData.integral" clearable />
          </el-form-item>
          <el-form-item label="奖惩日期:" prop="rewardDate" class="w50p">
            <el-date-picker
              v-model="formData.rewardDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间"
              clearable
            />
          </el-form-item>
          <el-form-item label="具体内容:" prop="details" class="w100p">
            <el-input v-model="formData.details" clearable />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import tenantInfoManage from "@/api/digital-operation/tenant-manage/tenant-info";
import awardPunishManage from "@/api/digital-operation/tenant-manage/award-punish-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

export default {
  name: "AwardPunishManage",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
    StartTimeEndTimeSelectionBox
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '信息类别',
          prop: 'category',
          type: 'select',
          options: [
            { label: '奖励', value: 'REWARD' },
            { label: '惩罚', value: 'PUNISH' },
          ],
          optionKey: { label: 'label', value: 'value' },
        }, {
          label: '承租户姓名',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lessesArr
          optionKey: { label: 'lesseeName', value: 'lesseeNo' },
        }, {
          label: '日期选择',
          prop: 'date',
          type: 'daterange',
        }, 
      ],
      searchlist: {},
      // 承租户Id
      lesseeNo: undefined,
      // 信息类别
      category: undefined,
      // 是否能输入
      // 承租户数组
      lessesArr: [],
      // 选中的数据项数组 ID组成
      rewardRecordIdList: [],
      rules: {
        category: [
          { required: true, message: "请选择信息类别", trigger: "change" }
        ],
        lesseeNo: [
          { required: true, message: "请选择姓名", trigger: "change" }
        ],
        details: [
          { required: true, message: "请输入具体内容", trigger: "blur" }
        ],
        rewardDate: [
          { required: true, message: "请选择奖惩时间", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 查询所有承租户
    this.queryLessesByCondition();
  },
  mounted() {
    // 获取表格数据
    this.getTableDataList();
  },
  methods: {
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          lesseeNo: this.searchlist.lesseeNo || undefined,
          category: this.searchlist.category || undefined,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          // endTime: this.endTime || undefined,
          // startTime: this.startTime || undefined
        }
      };
      awardPunishManage.getLessesRewardList(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
      this.tableData.forEach(item => {
        this.lessesArr.forEach(itemTwo => {
          if (item.lesseeNo === itemTwo.lesseeNo) {
            this.$set(item, "lessee", itemTwo.lessee);
          }
        });
      });
    },
    // 时间转换
    dateFormat(row, colnum) {
      if (row.rewardDate) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    // 条件查询所有承租户
    async queryLessesByCondition() {
      const { data: res } = await tenantInfoManage.queryLessesByCondition(1);
      // console.log(res);
      this.lessesArr = res;
      this.setOptions(this.formConfig, 'lesseeNo', res)
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e || undefined;
    },
    endVal(e) {
      this.endTime = e || undefined;
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify(row));
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
      // this.$refs.formData.resetFields()
    },
    handleSelectionChange(list) {
      this.rewardRecordIdList = [];
      this.rewardRecordIdList = list.map(item => item.rewardRecordId);
      if (this.rewardRecordIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage(formData) {
      awardPunishManage.delLessesReward(this.rewardRecordIdList).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          // this.$refs[formData].resetFields();
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
      this.resetActionBar();
    },
    handleDelete(val) {
      // awardPunishManage.delLessesReward([val]).then((res) => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   } else {
      //     this.$message.warning(res.msg || "删除失败");
      //   }
      // });
      // this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          awardPunishManage.delLessesReward([val]).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.getTableDataList();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            awardPunishManage.editLessesReward(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                // this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败!");
              }
            });
          } else if (this.nowChanceStau === "add") {
            awardPunishManage.addLessesReward(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功!");
                // this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败!");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .label {
  text-align: end;
  padding: 0 10px;
}
::v-deep .el-form {
  .el-form-item__label {
    min-width: 100px !important;
  }
}
</style>
